import Taro from "@tarojs/taro";
const BASE_URL = process.env.TARO_APP_API;
const TIMEOUT = 10000; // 超时时间

const http = (options) => {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: BASE_URL + options.url,
      method: options.method || "GET",
      data: options.data || {},
      header: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${Taro.getStorageSync("token") || ""}`,
        ...options.header,
      },
      timeout: TIMEOUT,
    })
      .then((response) => {
        if (response.statusCode === 200) {
          resolve(response.data);
        } else {
          Taro.showToast({
            title: response.data.message || "请求失败",
            icon: "none",
          });
          reject(response.data);
        }
      })
      .catch((error) => {
        Taro.showToast({ title: "网络错误，请稍后重试", icon: "none" });
        reject(error);
      });
  });
};

export default {
  get(url, data = {}, header = {}) {
    return http({ url, method: "GET", data, header });
  },
  post(url, data = {}, header = {}) {
    return http({ url, method: "POST", data, header });
  },
  put(url, data = {}, header = {}) {
    return http({ url, method: "PUT", data, header });
  },
  delete(url, data = {}, header = {}) {
    return http({ url, method: "DELETE", data, header });
  },
};
